package babo.cd.physicalexperiment.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureCropParameterStyle;
import com.luck.picture.lib.style.PictureParameterStyle;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import babo.cd.physicalexperiment.MainActivity;
import babo.cd.physicalexperiment.R;
import babo.cd.physicalexperiment.activity.AboutUsActivity;
import babo.cd.physicalexperiment.activity.LoginActivity;
import babo.cd.physicalexperiment.activity.NoticeListActivity;
import babo.cd.physicalexperiment.activity.SettingActivity;
import babo.cd.physicalexperiment.activity.ShebeiListActivity;
import babo.cd.physicalexperiment.activity.ShiyanHistoryiListActivity;
import babo.cd.physicalexperiment.app.MyApplication;
import babo.cd.physicalexperiment.bean.JustDataBean;
import babo.cd.physicalexperiment.bean.UserInfoBean;
import babo.cd.physicalexperiment.data.UserInfo;
import babo.cd.physicalexperiment.databinding.FragmentMineBinding;
import babo.cd.physicalexperiment.utils.DataCleanManager;
import babo.cd.physicalexperiment.utils.GlideEngine;
import babo.cd.physicalexperiment.utils.OKCallback;
import babo.cd.physicalexperiment.utils.OkUtils;
import babo.cd.physicalexperiment.utils.Out;
import babo.cd.physicalexperiment.utils.URLS;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

public class MineFragment extends BaseFragment {
    FragmentMineBinding binding;
    File tempFile;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    @Override
    public View getLayout() {
        binding=FragmentMineBinding.inflate(getLayoutInflater());

        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        getMyUserInfo();
    }

    private void getMyUserInfo() {
        OkUtils.GetOk(URLS.getUserInfo,new OKCallback(getActivity()){
            @Override
            public void Eorror(int code) {
                super.Eorror(code);
                if (code==401){
                    UserInfo.userId="";
                    UserInfo.JsessionId="";
                    Intent intent=new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }
            }

            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                Out.out("用户信息："+str);
                Gson gson=new Gson();
                UserInfoBean userInfoBean=gson.fromJson(str,UserInfoBean.class);
                MyApplication.getInstance().setUserBaseInfo(userInfoBean.getData());
                try {
                    if (userInfoBean.getData().getMessageCount()>0){
                        ((MainActivity)getActivity()).setMssageNum(userInfoBean.getData().getMessageCount());
                        binding.rlMsgcount.setVisibility(View.VISIBLE);
                        binding.txCount.setVisibility(View.VISIBLE);
                        binding.txCount.setText(userInfoBean.getData().getMessageCount()+"");
                    }else{
                        binding.rlMsgcount.setVisibility(View.GONE);
                        ((MainActivity)getActivity()).setMssageNum(0);
                    }

                }catch (Exception ex){

                }

            }

        });
    }

    @Override
    public void onConfigurationChanged(@NonNull @NotNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getMyUserInfo();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        getMyUserInfo();
    }

    @Override
    public void initView() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, 123);
            }
        }
    }

    @Override
    public void initData() {
        String totalCacheSize = DataCleanManager.getTotalCacheSize(getActivity());
        if (!TextUtils.isEmpty(totalCacheSize)) {
            binding.txHcsl.setText(totalCacheSize);
        }else {
            binding.txHcsl.setText("");
        }
        binding.txName.setText(MyApplication.getInstance().getUserBaseInfo().getName());
        binding.txSex.setText("手机号"+MyApplication.getInstance().getUserBaseInfo().getMobile());
        Glide.with(getActivity()).load(MyApplication.getInstance().getUserBaseInfo().getAvatar()).into(binding.ivHead);
          String role=MyApplication.getInstance().getUserBaseInfo().getRole().toUpperCase();
          if (role.contains("ADMIN")){
              binding.rlShebei.setVisibility(View.VISIBLE);
          }else{
              binding.rlShebei.setVisibility(View.GONE);
          }
//        int color1=Color.parseColor("#b7bbd9");
//        int color2=Color.parseColor("#800000");
//        int color3=Color.parseColor("#5CACEE");
////
//        int [] cls={color1,color3};
////
//        GradientDrawable gradientDrawable=new GradientDrawable();
//        gradientDrawable.setColors(cls);
//        gradientDrawable.setShape(GradientDrawable.RECTANGLE);
//        gradientDrawable.setGradientType( GradientDrawable.LINEAR_GRADIENT);
//        gradientDrawable.setOrientation(GradientDrawable.Orientation.RIGHT_LEFT);
//        binding.rlSet.setBackground(gradientDrawable);
    }

    @Override
    public void setListener() {

        binding.rlHistory.setOnClickListener(v -> {
            goToNextActivity(ShiyanHistoryiListActivity.class);
        });
    binding.rlAbout.setOnClickListener(v -> {
        goToNextActivity(AboutUsActivity.class);
    });
    binding.ivHead.setOnClickListener(view -> {
        doSelectImg();
    });
    binding.rlSet.setOnClickListener(v -> {
            goToNextActivity(SettingActivity.class);
        });
        binding.rlShebei.setOnClickListener(v -> {
            goToNextActivity(ShebeiListActivity.class);
        });
        binding.rlMessage.setOnClickListener(v -> {
            goToNextActivity(NoticeListActivity.class);
        });

   binding.rlJianchagengxin.setOnClickListener(v -> {
       Out.toast(getActivity(),"当前已经是最新版本！");
   });
   binding.rlQchc.setOnClickListener(v -> {
       DataCleanManager.clearAllCache(getActivity());
       String totalCacheSize = DataCleanManager.getTotalCacheSize(getActivity());
       if (!TextUtils.isEmpty(totalCacheSize)) {
           binding.txHcsl.setText(totalCacheSize);
       }else {
           binding.txHcsl.setText("");
       }
   });
    }
    private void doSelectImg() {
        PictureParameterStyle mPictureParameterStyle = new PictureParameterStyle();
// 是否改变状态栏字体颜色(黑白切换)
        mPictureParameterStyle.isChangeStatusBarFontColor = false;
// 是否开启右下角已完成(0/9)风格
        mPictureParameterStyle.isOpenCompletedNumStyle = false;
// 是否开启类似QQ相册带数字选择风格
        mPictureParameterStyle.isOpenCheckNumStyle = true;
// 相册状态栏背景色
        mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#393a3e");
// 相册列表标题栏背景色
        mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#393a3e");
// 相册列表标题栏右侧上拉箭头
        mPictureParameterStyle.pictureTitleUpResId = R.drawable.picture_icon_arrow_up;
// 相册列表标题栏右侧下拉箭头
        mPictureParameterStyle.pictureTitleDownResId = R.drawable.picture_icon_arrow_down;
// 相册文件夹列表选中圆点
        mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval;
// 相册返回箭头
        mPictureParameterStyle.pictureLeftBackIcon = R.drawable.picture_icon_back;
// 标题栏字体颜色
        mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(getActivity(), R.color.picture_color_white);
// 相册右侧取消按钮字体颜色
        mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(getActivity(), R.color.picture_color_white);
// 相册列表勾选图片样式
        mPictureParameterStyle.pictureCheckedStyle = R.drawable.picture_checkbox_selector;
// 选择相册目录背景样式

// 相册列表底部背景色
        mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(getActivity(), R.color.picture_color_fa);
// 已选数量圆点背景样式
        mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.picture_num_oval;
// 相册列表底下预览文字色值(预览按钮可点击时的色值)
        mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(getActivity(), R.color.picture_color_fa632d);
// 相册列表底下不可预览文字色值(预览按钮不可点击时的色值)
        mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(getActivity(), R.color.picture_color_9b);
// 相册列表已完成色值(已完成 可点击色值)
        mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(getActivity(), R.color.picture_color_fa632d);
// 相册列表未完成色值(请选择 不可点击色值)
        mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(getActivity(), R.color.picture_color_9b);
// 预览界面底部背景色
        mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(getActivity(), R.color.picture_color_grey_3e);
// 外部预览界面删除按钮样式
        mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_delete;
// 外部预览界面是否显示删除按钮
        mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true;
// 相册右侧按钮背景样式,只针对isWeChatStyle 为true时有效果
        mPictureParameterStyle.pictureUnCompleteBackgroundStyle = R.drawable.picture_send_button_default_bg;
// 相册右侧按钮可点击背景样式,只针对isWeChatStyle 为true时有效果
        mPictureParameterStyle.pictureCompleteBackgroundStyle = R.drawable.picture_send_button_bg;

// 以下设置如果用不上则不要设置，使用默认即可
// 自定义相册右侧文本内容设置
        mPictureParameterStyle.pictureRightDefaultText = "";
// 自定义相册未完成文本内容
        mPictureParameterStyle.pictureUnCompleteText = "";
// 完成文案是否采用(%1$d/%2$d)的字符串，只允许两个占位符哟
        mPictureParameterStyle.isCompleteReplaceNum = true;
// 自定义相册完成文本内容
        mPictureParameterStyle.pictureCompleteText = "";
// 自定义相册列表不可预览文字
        mPictureParameterStyle.pictureUnPreviewText = "";
// 自定义相册列表预览文字
        mPictureParameterStyle.picturePreviewText = "";
// 自定义相册标题字体大小
        mPictureParameterStyle.pictureTitleTextSize = 18;
// 自定义相册右侧文字大小
        mPictureParameterStyle.pictureRightTextSize = 14;
// 自定义相册预览文字大小
        mPictureParameterStyle.picturePreviewTextSize = 14;
// 自定义相册完成文字大小
        mPictureParameterStyle.pictureCompleteTextSize = 14;
// 自定义原图文字大小
        mPictureParameterStyle.pictureOriginalTextSize = 14;

// 裁剪主题
        PictureCropParameterStyle mCropParameterStyle = new PictureCropParameterStyle(
                ContextCompat.getColor(getActivity(), R.color.picture_color_grey),
                ContextCompat.getColor(getActivity(), R.color.picture_color_grey),
                ContextCompat.getColor(getActivity(), R.color.picture_color_white),
                mPictureParameterStyle.isChangeStatusBarFontColor);

        // 相册启动退出动画
        PictureWindowAnimationStyle windowAnimationStyle = new PictureWindowAnimationStyle();
        windowAnimationStyle.ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out);
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .maxSelectNum(1)
                .enableCrop(true)
                .setPictureStyle(mPictureParameterStyle)
                .selectionMode(PictureConfig.SINGLE)//
                .withAspectRatio(1, 1)
                .compress(true)// 是否压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    Glide.with(getActivity()).load(selectList.get(0).getCompressPath()).into(binding.ivHead);
                    tempFile=new File(selectList.get(0).getCompressPath());
                    post3(URLS.uploadImage,new OKCallback(getActivity()){
                        @Override
                        public void Sucess(String str) {
                            super.Sucess(str);
                            try {
                                Gson gson=new Gson();
                                JustDataBean justDataBean=gson.fromJson(str,JustDataBean.class);
                                Out.out("上传回来的头像："+justDataBean.getData());
                                uploadUsrInfo(justDataBean.getData());
                            }catch (Exception ex){
                                ex.printStackTrace();
                            }
                        }
                    },null,tempFile,null,null,UserInfo.JsessionId);
                    break;

            }
        }
    }
    private void uploadUsrInfo(String data) {
        LinkedHashMap hashMap=new LinkedHashMap();
        hashMap.put("id",UserInfo.userId);
        hashMap.put("avatar",data);

        OkUtils.performByJsonArray(getActivity(),URLS.uploadUserInfo,hashMap,2,new OKCallback(getActivity()){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                MyApplication.getInstance().getUserBaseInfo().setAvatar(data);
                Out.toast(getActivity(),"修改成功！");
            }
        });
    }
    public static void post3(String address, okhttp3.Callback callback, Map<String, String> map, File mfile, File mfile2, File mfile3, String token) {

        address= URLS.HTTPHEAD+address;
        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }


        if (mfile != null) {


            String TYPE = "application/octet-stream";
            RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), mfile);
            RequestBody requestBody = builder
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("image ", mfile.getName(), fileBody)
                    .build();
            Request request = new Request.Builder()
                    .url(address)
                    .post(requestBody)
                    .addHeader("Cookie", "JSESSIONID="+ UserInfo.JsessionId)
                    .build();
            client.newCall(request).enqueue(callback);
            Out.out("开始网络请求没111=="+address);

        } else {
//            Log.d(TAG, "post3: 文件不存在");
//            RequestBody requestBody = builder
//                    .setType(MultipartBody.FORM)
//                    .build();
//            Request request = new Request.Builder()
//                    .url(address)
//                    .post(requestBody)
//                    .addHeader("Cookie", "JSESSIONID="+ UserInfo.JsessionId)
//                    .build();
//            client.newCall(request).enqueue(callback);
            Out.out("开始网络请求没：000---"+address);
        }

    }
}
